//
//  QSHomeViewController.m
//  DigitalEconomy_iOS
//
//  Created by Ding on 2020/3/17.
//  Copyright © 2020 DingC. All rights reserved.
//

#import "QSHomeViewController.h"
#import "QSHomeHeaderView.h"
#import "QSHomeMassageCell.h"
#import "QSMyInfoViewController.h"
#import "QSNotificationCenterController.h"
#import "QSEnterpriseSignInController.h"
#import "QSEnterpriseVisitViewController.h"
#import "QSProblemSeportViewController.h"
#import "QSProblemProcessingViewController.h"
#import "QSUserInterface.h"
#import "QSLeadCockpitViewController.h"
#import "QSEnterpriseArchivesViewController.h"
#import "QSHomeInterface.h"
#import "QSNotificationDetailsViewController.h"
#import "QSMessageDetailModel.h"
#import "QSMessageDetailViewController.h"
#import "QSWebViewController.h"
#import "QSAddVisitViewController.h"
@interface QSHomeViewController ()<UITableViewDelegate, UITableViewDataSource, QSHomeHeaderViewDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property (nonatomic, strong)QSHomeHeaderView *headerView;

@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)NSMutableArray *dataArr;

@property (nonatomic, assign)NSInteger pageIndex;

@property (nonatomic, assign)NSInteger unReadNum;
@end
static NSString *cellId = @"HomeMessageCell";
@implementation QSHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
    [self configSubView];
    [self addRefreshHeader];
    [self addRefreshFooter];
}

- (void)configSubView{
    [self.view addSubview:self.headerView];
    [self.view addSubview:self.tableView];
//    self.tabBarController.tabBar.hidden = YES;

    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_bottom).offset(kRealValue(10));
        make.left.right.equalTo(self.view);
        if (self.tabBarController.tabBar.hidden) {
            make.bottom.equalTo(self.view);
        }else{
            make.bottom.equalTo(self.view).offset(- kTabBarHeight);
        }
    }];
}

#pragma mark -- 懒加载
- (QSHomeHeaderView *)headerView{
    if (!_headerView) {
        _headerView = [[QSHomeHeaderView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth * kHomeHeaderProportion + kStatusBarHeight + kRealValue(80))];
        _headerView.delegate = self;
        WeakSelf(weakSelf);
        weakSelf.headerView.headerBackgroundImageView.userInteractionEnabled = NO;
        weakSelf.headerView.headerBackgroundImageView.image = [UIImage imageNamed:@"ic_newhomeHeader"];
        weakSelf.headerView.nameLabel.hidden = YES;
        weakSelf.headerView.enterpriseLabel.hidden = YES;
        weakSelf.headerView.rightImageView.hidden = YES;
        weakSelf.headerView.userIconImageView.hidden = YES;
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            weakSelf.headerView.height = weakSelf.headerView.notificationButton.maxY + weakSelf.headerView.notificationButton.height;
//        });
    }
    return _headerView;
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.layer.cornerRadius = 5;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"QSHomeMassageCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:cellId];
    }
    return _tableView;
}

- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

#pragma mark -- TableViewDelegate

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc]init];
    UILabel *titleLabel = [UILabel labelWithName:@"我的消息提醒" font:[UIFont systemFontOfSize:16 weight:1] textColor:[UIColor QSColorBlack434343] textAlignment:NSTextAlignmentLeft];
    [headerView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(headerView);
        make.left.equalTo(headerView).offset(kRealValue(13));
    }];
    
    UILabel *messageNumLabel = [UILabel labelWithName:@"" font:[UIFont QSFontOfSize12] textColor:[UIColor QSColorWhiteFFFFFF] textAlignment:NSTextAlignmentCenter];
    if (!_unReadNum || _unReadNum == 0) {
        messageNumLabel.hidden = YES;
    }else{
        if (_unReadNum >= 100) {
            messageNumLabel.text = @"···";
        }else{
            messageNumLabel.text = [NSString stringWithFormat:@"%ld", (long)_unReadNum];
        }
    }
    messageNumLabel.backgroundColor = [UIColor colorWithHexString:@"#FF3636"];
    messageNumLabel.layer.cornerRadius = 8;
    messageNumLabel.layer.masksToBounds = YES;
    [headerView addSubview:messageNumLabel];
    [messageNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(titleLabel);
        make.left.equalTo(titleLabel.mas_right).offset(kRealValue(6));
        make.height.offset(kRealValue(16));
        make.width.offset(kRealValue(30));
    }];
    headerView.backgroundColor = [UIColor QSColorWhiteFFFFFF];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return kRealValue(36);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return kRealValue(73.5);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QSHomeMassageCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell) {
        cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    }
    cell.detailModel = self.dataArr[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    [QSUserInterface getUserisEnterprisePersonandBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSDictionary * _Nonnull result) {
//
//    }];
    QSMessageDetailModel *model = self.dataArr[indexPath.row];
    QSMessageDetailViewController *vc = [QSMessageDetailViewController new];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
}

#pragma mark - HeaderViewDelegate
//点击背景图
- (void)homeHeaderView:(QSHomeHeaderView *)headerView didSelectBackgroundPicture:(NSInteger)subIndex{
    QSMyInfoViewController *vc = [QSMyInfoViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}
//点击通知Button
- (void)homeHeaderViewDidClickNotificationButton:(QSHomeHeaderView *)headerView{
    QSNotificationCenterController *vc = [QSNotificationCenterController new];
    [self.navigationController pushViewController:vc animated:YES];
}
//点击通知标题
- (void)homeHeaderViewDidClickNotificationTitle:(QSHomeHeaderView *)headerView imId:(NSInteger)imId{
    QSNotificationDetailsViewController *vc = [QSNotificationDetailsViewController new];
    vc.imId = imId;
    [self.navigationController pushViewController:vc animated:YES];
}
//点击导航item
- (void)homeHeaderView:(QSHomeHeaderView *)headerView navigationCollectionViewdidSelectItemAtIndexPath:(NSIndexPath *)indexPath
                itemModel:(QSItemModel *)itemModel{
    if ([itemModel.label isEqualToString:@"领导驾驶舱"]) {
        QSWebViewController *web = [[QSWebViewController alloc] init];
        web.URLString = [NSString stringWithFormat:@"%@/leader_drive.html#/Home?allToken=%@&platform=iOS", kLeaderDriveH5Prefix, kCurrentUser.allToken];
        web.hideNavigationBar = YES;
        [self.navigationController pushViewController:web animated:YES];
    }
    if ([itemModel.label isEqualToString:@"一企一档"]) {
        QSEnterpriseArchivesViewController *vc = [QSEnterpriseArchivesViewController new];
        vc.strUrl = [NSString stringWithFormat:@"%@#/home?allToken=%@&platform=iOS", KH5Prefix, kCurrentUser.allToken];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([itemModel.label isEqualToString:@"驻企签到"]) {
        QSEnterpriseSignInController *vc = [QSEnterpriseSignInController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([itemModel.label isEqualToString:@"企业走访"]) {
        QSEnterpriseVisitViewController *vc = [QSEnterpriseVisitViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([itemModel.label isEqualToString:@"问题处理"]) {
        QSProblemProcessingViewController *vc = [QSProblemProcessingViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([itemModel.label isEqualToString:@"问题上报"]) {
        QSProblemSeportViewController *vc = [QSProblemSeportViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([itemModel.label isEqualToString:@"新增走访"]) {
         QSAddVisitViewController *vc = [QSAddVisitViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
    //新增
    if ([itemModel.label isEqualToString:@"政策宝典"]) {
        QSWebViewController *web = [[QSWebViewController alloc] init];
//        http://test-control-h5.test176.cn/policy-suggestion-H5_index.html#/home

        web.URLString = [NSString stringWithFormat:@"%@/policy-suggestion-H5_index.html#/home?allToken=%@&platform=iOS",
                         KH5Prefix, kCurrentUser.allToken];
        web.hideNavigationBar = YES;
        [self.navigationController pushViewController:web animated:YES];
    }
    if ([itemModel.label isEqualToString:@"企业运行监测"]) {
        QSWebViewController *web = [[QSWebViewController alloc] init];
    //        http://test-control-h5.test176.cn/enterprise_operation_index.html#/home

        web.URLString = [NSString stringWithFormat:@"%@/enterprise_operation_index.html#/home?allToken=%@&platform=iOS",
                         KH5Prefix, kCurrentUser.allToken];
        web.hideNavigationBar = YES;
        [self.navigationController pushViewController:web animated:YES];
//        [QSAppKeyWindow showAutoHideHudWithText:itemModel.label];
    }
//    switch ([itemModel.key integerValue]) {
//        case 1:
//        {//领导驾驶舱
////            QSLeadCockpitViewController *vc = [[QSLeadCockpitViewController alloc]initWithNibName:@"QSLeadCockpitViewController" bundle:[NSBundle mainBundle]];
////            [self.navigationController pushViewController:vc animated:YES];
//            QSWebViewController *web = [[QSWebViewController alloc] init];
//            web.URLString = [NSString stringWithFormat:@"%@/leader_drive.html#/Home?allToken=%@&platform=iOS", kLeaderDriveH5Prefix, kCurrentUser.allToken];
//            web.hideNavigationBar = YES;
//            [self.navigationController pushViewController:web animated:YES];
//        }
//            break;
//        case 2://一企一档
//        {
////            QSWebViewController *web = [[QSWebViewController alloc] init];
////            web.URLString = [NSString stringWithFormat:@"%@#/hocme?allToken=%@&platform=iOS", KH5Prefix, kCurrentUser.allToken];
////            web.hideNavigationBar = YES;
////            [self.navigationController pushViewController:web animated:YES];
//            QSEnterpriseArchivesViewController *vc = [QSEnterpriseArchivesViewController new];
//            [self.navigationController pushViewController:vc animated:YES];
//        }
//            break;
//        case 3://驻企签到
//        {
//            QSEnterpriseSignInController *vc = [QSEnterpriseSignInController new];
//            [self.navigationController pushViewController:vc animated:YES];
//        }
//
//            break;
//        case 4://企业走访
//        {
//            QSEnterpriseVisitViewController *vc = [QSEnterpriseVisitViewController new];
//            [self.navigationController pushViewController:vc animated:YES];
//        }
//            break;
//        case 5://问题处理
//        {
//            QSProblemProcessingViewController *vc = [QSProblemProcessingViewController new];
//            [self.navigationController pushViewController:vc animated:YES];
//        }
//            break;
//        case 6://问题上报
//        {
//            QSProblemSeportViewController *vc = [QSProblemSeportViewController new];
//            [self.navigationController pushViewController:vc animated:YES];
//        }
//            break;
//
//        default:
//            break;
//    }
}

#pragma mark - Api Request



- (void)addRefreshHeader {
    WeakSelf(weakSelf);
    [self.tableView addRefreshHeaderWithRefreshingBlock:^{
        weakSelf.pageIndex = 1;
        [weakSelf tableViewShouldUpdateDataByPageIndex:weakSelf.pageIndex];
    }];
}

- (void)addRefreshFooter {
    WeakSelf(weakSelf);
    [self.tableView addRefreshFooterWithRefreshingBlock:^{
        weakSelf.pageIndex ++;
        [weakSelf tableViewShouldUpdateDataByPageIndex:weakSelf.pageIndex];
    }];
}

- (void)startRefreshing {
    [self startRefreshing:NO];
}

- (void)startRefreshing:(BOOL)animated {
    self.pageIndex = 1;
    if (animated) {
        [self.tableView qs_startRefreshing];
    } else {
        [self tableViewShouldUpdateDataByPageIndex:self.pageIndex];
    }
}

- (void)requestUnReadMessageNum{
    [QSHomeInterface getUnReadMessageNumandBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSDictionary * _Nonnull result) {
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            NSLog(@"%@", result);
            if (result) {
                self.unReadNum = [result[@"count"] integerValue];
                [self.tableView reloadData];
            }
        }
    }];
}

- (void)tableViewShouldUpdateDataByPageIndex:(NSInteger)pageIndex {
    [self requestUnReadMessageNum];
    [self.tableView qs_endRefreshing];
    [QSHomeInterface getMessageListWithPageIndex:pageIndex andBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, QSMessageListModel * _Nonnull resultModel) {
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            if (pageIndex == 1) {
                [self.dataArr removeAllObjects];
            }
            [self.dataArr addObjectsFromArray:resultModel.list];
            self.tableView.emptyDataSetSource = self;
            self.tableView.emptyDataSetDelegate = self;
            [self.tableView reloadData];
            [self.tableView qs_endRefreshing];
            if (pageIndex >= resultModel.pages) {
//                self.tableView.mj_footer.hidden = YES;
                [self.tableView qs_endRefreshingWithNoMoreData];
            }
        }
    }];
  
    [self.headerView loadData];
}

#pragma mark - DZNEmptyDataSetSource
/**
 *  返回标题文字
 */
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text = @"您还没有消息!";
    NSDictionary *attributes = @{ NSFontAttributeName: [UIFont boldSystemFontOfSize:14.0f],
                                     NSForegroundColorAttributeName: [UIColor QSColorBlack666666] };
    return [[NSAttributedString alloc]initWithString:text attributes:attributes];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    scrollView.backgroundColor = [UIColor QSColorWhiteFFFFFF];
    return [UIImage imageNamed:@"ic_nullimage"];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
//    [self requestUnReadMessageNum];//请求消息数量
    [self startRefreshing];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
